import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { GatewayService } from './gateway.service';
import { NacosModule } from 'libs/nacos/nacos.module';
import nacos from 'config/nacos';
import serverConfig from '../config';
import { NacosNamingClientService } from 'libs/nacos/nacosNamingClient.service';
import AuthApi from './api/auth.api';
import { ProxyMiddleware } from './middleware/gateway.middleware';

@Module({
  imports: [
    NacosModule.forRoot({
      clientOptions: { //配置中心
        serverAddr: nacos.url,
        namespace: nacos.namespace,
      },
      nacosNamingClientConfig: {  //服务注册发现
        logger: console,
        serverList: nacos.url,
        namespace: nacos.namespace,
      }
    })
  ],
  controllers: [],
  providers: [GatewayService,AuthApi]
})
export class GatewayModule implements NestModule {
  constructor(readonly nacosNamingClientService: NacosNamingClientService) {
    //项目启动时注入服务
    nacosNamingClientService.registerInstance({
      serviceName: serverConfig.serviceName,
      instance: {
        ip: serverConfig.ip,
        port: serverConfig.port,
        instanceId: serverConfig.serviceId,
        healthy: true,
        enabled: true,
      }
    })
  }

  configure(consumer:MiddlewareConsumer){
    consumer
    .apply(ProxyMiddleware)
    .forRoutes('*')
  }
}
